package com.nami.client.network.codec;


import com.nami.basic.packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;



/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-14 13:19
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class WsMessageDecoder extends MessageToMessageDecoder<BinaryWebSocketFrame> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, BinaryWebSocketFrame frame, List<Object> out) throws Exception {
        ByteBuf byteBuf = frame.content();
        if (byteBuf == null || !byteBuf.isReadable()) {
            log.error("缓冲区不可读！");
            throw new IllegalArgumentException("缓冲区不可读！");
        }
        if (byteBuf.readableBytes() < 12) {
            return;
        }
        // 读索引必须从头开始读的，这样才能保证是第一次读取
        int readerIndex = byteBuf.readerIndex();
        if (readerIndex != 0) {
            return;
        }
        decode0(out, byteBuf);
    }

    private static void decode0(List<Object> out, ByteBuf byteBuf) {
        // 对其填充
        byte magic = byteBuf.readByte();
        // cmd
        int cmd = byteBuf.readInt();
        // 版本号
        byte version = byteBuf.readByte();

        // 设备类型
        // 设备类型 登录以参数传入
//        byte deviceType = byteBuf.readByte();

        // 加密类型
        byte encrypt = byteBuf.readByte();

        byte serial = byteBuf.readByte();

        // 子包体长度
        int length = byteBuf.readInt();

        Packet packet = new Packet();
        packet.setMagic(magic);
        packet.setCmd(cmd);
        packet.setVersion(version);
//        message.setDeviceType(deviceType);
        packet.setEncrypt(encrypt);
        packet.setSerial(serial);
        packet.setLength(length);
//        log.info("[nami-decoder] 解析：{}", JsonUtils.toJsonString(namiPack));
        byte[] body = new byte[length];
        //将消息内容n个字节读到字节数组中
        byteBuf.readBytes(body);
        packet.setBody(body);
        out.add(packet);
    }
}
